<template>
  <a-form
    :model="formSearchParams"
    :style="{ marginBottom: '20px' }"
    layout="inline"
    @submit="doSearch"
  >
    <a-form-item field="userName" label="用户名">
      <a-input
        allow-clear
        v-model="formSearchParams.userName"
        placeholder="请输入用户名"
      />
    </a-form-item>
    <a-form-item field="userProfile" label="用户简介">
      <a-input
        allow-clear
        v-model="formSearchParams.userProfile"
        placeholder="请输入用户简介"
      />
    </a-form-item>
    <a-form-item>
      <a-button type="primary" html-type="submit" style="width: 100px">
        搜索
      </a-button>
    </a-form-item>
  </a-form>
  <a-table
    :columns="columns"
    :data="dataList"
    :pagination="{
      showTotal: true,
      pageSize: searchParams.pageSize,
      current: searchParams.current,
      total,
    }"
    @page-change="onPageChange"
  >
    <template #userAvatar="{ record }">
      <a-image width="64" :src="record.userAvatar" />
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button status="primary" @click="doEdit(record)">编辑</a-button>
        <a-button status="danger" @click="doDelete(record)">删除</a-button>
      </a-space>
    </template>
  </a-table>
  <a-modal
    v-model:visible="isModalVisible"
    title="编辑用户"
    @ok="handleSave"
    @cancel="handleCancel"
  >
    <a-form :model="editForm" layout="vertical">
      <a-form-item label="用户名">
        <a-input v-model="editForm.userName" />
      </a-form-item>
      <a-form-item label="用户简介">
        <a-input v-model="editForm.userProfile" />
      </a-form-item>
      <a-form-item label="账号">
        <a-input v-model="editForm.userAccount" />
      </a-form-item>
      <a-form-item label="权限">
        <a-input v-model="editForm.userRole" />
      </a-form-item>
      <a-form-item label="用户部门">
        <a-input v-model="editForm.department" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import {
  deleteUserUsingPost,
  listUserByPageUsingPost,
  updateUserUsingPost,
  editUserUsingPost,
} from "@/api/userController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";

const formSearchParams = ref<API.UserQueryRequest>({});

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

const searchParams = ref<API.UserQueryRequest>({
  ...initSearchParams,
});
const dataList = ref<API.User[]>([]);
const total = ref<number>(0);

// 模态框相关变量
const isModalVisible = ref(false);
const editForm = ref<API.UserQueryRequest>({});

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listUserByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

/**
 * 执行搜索
 */
const doSearch = () => {
  searchParams.value = {
    ...initSearchParams,
    ...formSearchParams.value,
  };
};

/**
 * 当分页变化时，改变搜索条件，触发数据加载
 * @param page
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.User) => {
  if (!record.id) {
    return;
  }

  const res = await deleteUserUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败，" + res.data.message);
  }
};

/**
 * 编辑
 * @param record
 */
const doEdit = async (record: API.User) => {
  if (!record.id) {
    return;
  }
  // 将当前要编辑的用户信息赋值给 editForm
  editForm.value = { ...record };
  // 显示模态框
  isModalVisible.value = true;
};

/**
 * 保存
 */
const handleSave = async () => {
  const res = await updateUserUsingPost(editForm.value);
  if (res.data.code === 0) {
    message.success("更新成功");
    loadData();
  } else {
    message.error("更新失败，" + res.data.message);
  }
  isModalVisible.value = false;
};

/**
 * 取消
 */
const handleCancel = () => {
  isModalVisible.value = false;
  editForm.value = {}; // 清空表单数据
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 表格列配置
const columns = [
  {
    title: "账号",
    dataIndex: "userAccount",
  },
  {
    title: "用户名",
    dataIndex: "userName",
  },
  {
    title: "权限",
    dataIndex: "userRole",
  },
  {
    title: "用户部门",
    dataIndex: "department",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    slotName: "createTime",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    slotName: "updateTime",
  },
  {
    title: "操作",
    slotName: "optional",
  },
];
</script>
